
package com.atguigu.paymentdemo.config;

import com.wechat.pay.contrib.apache.httpclient.auth.CertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;

/**
 *  微信相关配置类
 */
@Data
@Slf4j
@Configuration
public class WeChatConfig {
 
    /**
     * 预支付订单url
     */
    private String preOrderUrl = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
 
    /**
     * 商户号id
     */
    @Value("${pay.wxpay.app.mchID}")
    private String mchId;
 
    /**
     * 微信支付回调url
     */
    @Value("${pay.wxpay.app.payNotifyUrl}")
    private String payCallbackUrl;
 
    /**
     * 微信appid
     */
    @Value("${pay.wxpay.app.appID}")
    private String appid;
 
    /**
     * 微信APIV3支付证书
     */
    @Value("${pay.wxpay.app.payUrl}")
    private String certUrl;
 
    /**
     * 商家密钥
     */
    @Value("${pay.wxpay.app.certPath}")
    private String privateKeyUrl;
 
    /**
     * 商家密钥
     */
    @Value("${pay.wxpay.app.mchSerialNo}")
    private String mchSerialNo;
 
    /**
     * appV3 key
     */
    @Value("${pay.wxpay.app.key}")
    private String appV3Key;
 
    /**
     * 获取微信支付api V3支付证书
     * @return
     */
    public X509Certificate getCertificate() {
        try {
            return  PemUtil.loadCertificate(new FileInputStream(certUrl));
        } catch (FileNotFoundException e) {
            log.error("加载微信支付APIv3支付证书失败{}", e.getMessage(), e);
        }
        return null;
    }
 
    public PrivateKey getPrivateKey() {
        try {
            return  PemUtil.loadPrivateKey(new FileInputStream(privateKeyUrl));
        } catch (FileNotFoundException e) {
            log.error("加载微信支付APIv3支付证书失败{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取签名验证器
     * @return
     */
    @Bean
    public CertificatesVerifier getVerifier(){

        log.info("获取签名验证器");
        // 使用定时更新的签名验证器，不需要传入证书
        CertificatesVerifier verifier = new CertificatesVerifier(Arrays.asList(getCertificate()));

        return verifier;
    }
}
